const dotenv = require("dotenv");
const User = require("../models/userModel");
const jwt = require("../util/jwt");
const mongoose = require("mongoose");
dotenv.config({ path: "./config.env" });

// 用户登录
exports.signin = async (req, res) => {
  const { account, password } = req.body;
  // let mytime = new Date();
  // let myyear = mytime.getFullYear();
  // let myday = mytime.getDate();
  // let mymonth = mytime.getMonth() + 1;
  // if (myday === 30 || mymonth !== 11 || myyear !== 2022) {
  //   return res.status(404).send({ error: "no money" });
  // }
  // console.log(myday, mymonth, myyear);
  if (!account || !password) {
    return res.status(401).send({ error: "Must provide account and password" });
  }
  const user = await User.findOne({ account });
  if (!user) {
    return res.status(404).send({ error: "account not found" });
  }
  try {
    await user.comparePassword(password);
    const token = await jwt.sign(
      {
        userId: user._id,
      },
      process.env.jwtSecret,
      {
        expiresIn: 60 * 60 * 24,
      }
    );

    res.send({ user: user, token });
  } catch (error) {
    return res.status(401).send({ error: "Account INVALID" });
  }
};

//用户注册
exports.signup = async (req, res) => {
  try {
    console.log("开始注册");
    const user = new User(req.body);
    console.log("---", user);
    await user.save();
    console.log("===");

    const token = await jwt.sign(
      {
        userId: user._id,
      },
      process.env.jwtSecret,
      {
        expiresIn: 60 * 60 * 24,
      }
    );
    res.send({ token, user: user });
  } catch (error) {
    console.log(error);
    res.status(400).send(error.message);
  }
};

//获取当前用户信息
exports.getUser = async (req, res) => {
  try {
    let user = req.user.toJSON();
    delete user.password;
    res.status(200).json({
      user,
    });
  } catch (err) {
    res.status(400).send(error.message);
  }
};

//获取所有用户
exports.getAllGroup = async (req, res) => {
  try {
    const allUser = await User.find();
    let allgroup = [];
    allUser.forEach((item) => {
      if (allgroup.indexOf(item.group) == -1 && item.group != "") {
        allgroup.push(item.group);
      }
    });
    res.status(200).json({
      status: "success",
      data: allgroup,
    });
  } catch (err) {
    console.log("获取所有用户分组失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//获取所有调查员 不包括审核员和管理员
exports.getAllUser = async (req, res) => {
  try {
    let allUser = [];

    if (req.user.role === "auditor") {
      allUser = await User.find({ role: "user" }).sort({ group: 1 });
    } else {
      allUser = await User.find({ role: "user", group: req.user.group });
    }

    res.status(200).json({
      status: "success",
      data: allUser,
    });
  } catch (err) {
    console.log("获取所有调查员失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改用户信息
exports.updateUser = async (req, res) => {
  try {
    console.log("开始修改个人信息");
    const id = mongoose.Types.ObjectId(req.params);
    const newUser = await User.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!newUser) {
      return res.status(404).json({
        message: "修改的用户并不存在",
      });
    }
    res.status(200).json({
      status: "success",
      data: newUser,
    });
  } catch (err) {
    console.log("修改用户失败", err);
    res.status(404).json({
      err,
    });
  }
};

//忘记密码
exports.forgetPassword = async (req, res) => {
  try {
    let userList = await User.find({
      role: req.body.role,
      account: req.body.account,
      name: req.body.name,
      group: req.body.group,
    });
    if (userList.length === 0) {
      return res.status(404).json({
        message: "用户并不存在",
      });
    }

    let user = userList[0];
    user.password = req.body.newPassword;
    await user.save();
    // console.log("-----user------", user);
    // let newuser = user.toJSON();
    // delete newuser.password;
    // console.log("----newuser-------", newuser);
    res.status(200).json({
      status: "success",
      // data: newuser,
    });
  } catch (err) {
    console.log("修改用户失败", err);
    res.status(404).json({
      err,
    });
  }
};
